package handler

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"skedule-backend/service"
)

// TaskExecutionHandler 任务执行处理器
type TaskExecutionHandler struct {
	executionService *service.TaskExecutionService
}

// NewTaskExecutionHandler 创建任务执行处理器实例
func NewTaskExecutionHandler(executionService *service.TaskExecutionService) *TaskExecutionHandler {
	return &TaskExecutionHandler{
		executionService: executionService,
	}
}

// RegisterRoutes 注册路由
func (h *TaskExecutionHandler) RegisterRoutes(router *gin.Engine) {
	router.POST("/api/tasks/:id/execute", h.ExecuteTask)
	router.GET("/api/tasks/executions/:id", h.GetExecution)
}

// ExecuteTask 执行任务
func (h *TaskExecutionHandler) ExecuteTask(c *gin.Context) {
	taskID := c.Param("id")
	if taskID == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "Task ID is required",
		})
		return
	}

	response, err := h.executionService.ExecuteTask(taskID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"message": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, response)
}

// GetExecution 获取执行记录
func (h *TaskExecutionHandler) GetExecution(c *gin.Context) {
	executionID := c.Param("id")
	if executionID == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "Execution ID is required",
		})
		return
	}

	response, err := h.executionService.GetExecution(executionID)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"success": false,
			"message": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, response)
} 